package com.hancher.common.base;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.hancher.common.androidutil.StateBarUtil;
import com.hancher.plugins.hrlog.HrLogUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.disposables.Disposable;
import lombok.Getter;


/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2021/8/25 0025 0:01 <br/>
 * 描述 :
 */
public abstract class BaseActivity<B extends ViewBinding> extends AppCompatActivity {

    protected B binding;
    @Getter
    List<Disposable> disposables = new ArrayList<>();

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        HrLogUtil.printKeyEvent(event);
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setStateBar();
        super.onCreate(savedInstanceState);

        //bing 反射 200ms
        try {
            Type superclass = getClass().getGenericSuperclass();
            Class<B> aClass = (Class<B>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (B) method.invoke(null, getLayoutInflater());
            setContentView(binding.getRoot());
        } catch (InvocationTargetException e) {
            HrLogUtil.e(e.getTargetException());
        } catch (Exception e) {
            HrLogUtil.e(e);
        }

        initView(savedInstanceState);
        initListener();
        initData();
    }


    /**
     * 可以覆写，修改单个界面的状态栏颜色
     */
    public void setStateBar() {
        StateBarUtil.white(this);
    }

    protected void initData() {

    }

    protected void initListener() {

    }

    protected void initView(Bundle savedInstanceState) {

    }

    public AppCompatActivity getContext() {
        return this;
    }

    public AppCompatActivity getActivity() {
        return this;
    }

    @Override
    protected void onDestroy() {
        for (Disposable disposable : disposables) {
            if (!disposable.isDisposed()) {
                disposable.dispose();
            }
        }
        binding = null;
        super.onDestroy();
    }
}
